// 工具基类
class Tool {
  constructor(name, description, example) {
    this.name = name
    this.description = description
    this.example = example
  }

  async execute(xmlDoc, debug) {
    throw new Error('必须实现execute方法')
  }
}

// 打开URL工具
class OpenUrlTool extends Tool {
  constructor() {
    super('open_url', '打开网页', `<open_url>\n<url>网页URL</url>\n</open_url>`)
  }

  async execute(xmlDoc, debug) {
    const url = xmlDoc.getElementsByTagName('url')[0].textContent
    debug('解析到的URL:', url)
    const tab = await chrome.tabs.create({ url })
    debug('成功创建标签页:', tab)
    return `已成功打开网页: ${url}`
  }
}

// 网页截图工具
class CaptureScreenshotTool extends Tool {
  constructor() {
    super(
      'capture_screenshot',
      '网页截图',
      `<capture_screenshot></capture_screenshot>`
    )
  }

  async execute(xmlDoc, debug) {
    const tab = await chrome.tabs.query({ active: true, currentWindow: true })
    const dataUrl = await chrome.tabs.captureVisibleTab(tab[0].windowId, {
      format: 'png',
    })
    return dataUrl
  }
}

// 页面内容提取工具
class ExtractContentTool extends Tool {
  constructor() {
    super(
      'extract_content',
      '提取页面内容',
      `<extract_content></extract_content>`
    )
  }

  async execute(xmlDoc, debug) {
    const [tab] = await chrome.tabs.query({
      active: true,
      currentWindow: true,
    })
    const result = await chrome.scripting.executeScript({
      target: { tabId: tab.id },
      func: () => {
        return {
          title: document.title,
          text: document.body.innerText,
          html: document.documentElement.outerHTML,
        }
      },
    })
    return result[0].result
  }
}

// 网页翻译工具
class TranslatePageTool extends Tool {
  constructor() {
    super(
      'translate_page',
      '翻译页面',
      `<translate_page>\n<language>目标语言代码</language>\n</translate_page>`
    )
  }

  async execute(xmlDoc, debug) {
    const lang = xmlDoc.getElementsByTagName('language')[0].textContent
    const [tab] = await chrome.tabs.query({
      active: true,
      currentWindow: true,
    })
    await chrome.scripting.executeScript({
      target: { tabId: tab.id },
      func: (lang) => {
        document.body.style.transition = 'all 0.3s ease'
        document.body.style.filter = 'blur(5px)'
        setTimeout(() => {
          document.body.style.filter = 'none'
          document.body.setAttribute('translate', 'yes')
          document.documentElement.lang = lang
        }, 300)
      },
      args: [lang],
    })
    return `已将页面翻译为${lang}`
  }
}

// 暗黑模式切换工具
class ToggleDarkModeTool extends Tool {
  constructor() {
    super(
      'toggle_dark_mode',
      '切换暗黑模式',
      `<toggle_dark_mode></toggle_dark_mode>`
    )
  }

  async execute(xmlDoc, debug) {
    const [tab] = await chrome.tabs.query({
      active: true,
      currentWindow: true,
    })
    await chrome.scripting.executeScript({
      target: { tabId: tab.id },
      func: () => {
        const isDark = document.body.classList.toggle('dark-mode')
        if (isDark) {
          document.body.style.backgroundColor = '#1a1a1a'
          document.body.style.color = '#ffffff'
        } else {
          document.body.style.backgroundColor = '#ffffff'
          document.body.style.color = '#000000'
        }
      },
    })
    return '已切换暗黑模式'
  }
}

// 工具管理器
class ToolManager {
  constructor() {
    this.tools = [
      new OpenUrlTool(),
      new CaptureScreenshotTool(),
      new ExtractContentTool(),
      new TranslatePageTool(),
      new ToggleDarkModeTool(),
    ]
  }

  getToolDescriptions() {
    return this.tools.map((tool) => ({
      name: tool.name,
      description: tool.description,
      example: tool.example,
    }))
  }

  async executeTool(toolXml, debug) {
    try {
      debug('开始执行工具:', toolXml)
      const parser = new DOMParser()
      const xmlDoc = parser.parseFromString(toolXml, 'text/xml')
      const toolName = xmlDoc.documentElement.nodeName
      debug('解析到的工具名称:', toolName)

      const tool = this.tools.find((t) => t.name === toolName)
      if (!tool) {
        throw new Error(`未知的工具: ${toolName}`)
      }

      return await tool.execute(xmlDoc, debug)
    } catch (error) {
      debug('工具执行失败:', error)
      throw new Error(`工具执行失败: ${error.message}`)
    }
  }
}

// 导出工具管理器实例
const toolManager = new ToolManager()
export const toolDescriptions = toolManager.getToolDescriptions()
export const executeTool = toolManager.executeTool.bind(toolManager)
